C#.NET byte[] 的一个小问题

来源:百度知道 编辑:UC知道 时间:2024/05/25 00:38:01
把一个long写入到byte[]的前几个字节,然后从byte[]的前几个字节读出到另一个long里面。
是用SetValue和GetValue吗?我写的程序如下,出错了。
byte[] buffer = new byte[1024];
long l = 888;
buffer.SetValue(l, 0);
long l2 = (long)buffer.GetValue(0);

给你2个方法,需要添加引用
using System.Runtime.InteropServices;
/// <summary>
/// 把任意类型数据按字节读取到byte[]
/// </summary>
/// <param name="sIn">该类型的一个实例</param>
/// <param name="nLen">该类型的长度</param>
/// <returns>字节流</returns>
public static byte[] ToByte(object sIn, int nLen)
{
IntPtr psIn = IntPtr.Zero;
byte[] buffer = new byte[nLen];
try
{
psIn = Marshal.AllocHGlobal(nLen);
Marshal.StructureToPtr(sIn, psIn, true);
Marshal.Copy(psIn, buffer, 0, nLen);
}
finally
{
if (psIn != IntPtr.Zero) Marshal.FreeHGlobal(psIn);
}
return buffer;
}
//将字节流转成指定类型
public static object ToObject(byte[] rawdatas, Type anytype)
{
int rawsize = Marshal.SizeOf(anytype);
if (rawsize > rawdatas.Length) return null;
IntPtr buffer = Marshal.AllocHGlobal(rawsize);//分配指定大小的内存,返回一个指针
Ma